import { GameObject } from '@/assets/scripts/GameObject'
import { Particle } from '@/assets/scripts/Particle'
import { Fireball } from '@/assets/scripts/skill/Fireball'
import { Heal } from '@/assets/scripts/skill/Heal'
import { Flash } from '@/assets/scripts/skill/Flash'
import { useGameStore } from '@/store/game'
import { useUserStore } from '@/store/user'
export class Player extends GameObject {
    constructor(gameMap, info) {
        super()
        this.gameMap = gameMap
        this.info = info
        this.width = this.gameMap.ctx.canvas.width
        this.height = this.gameMap.ctx.canvas.height

        this.move_length = 0 // 移动长度
        this.vx = 0
        this.vy = 0
        this.damageX = 0
        this.damageY = 0
        this.damageSpeed = 0
        this.friction = 0.9
        this.spent_time = 0
        this.eps = 0.1 // 精度
        this.is_dead = false // 标记玩家是否已死亡
        this.current_skill = null // 当前技能
        // 最大血量
        this.maxHp = this.info.hp || 100
        
        // 初始化技能系统（对于所有类型的玩家）
        this.initialize_skills();
        
        // 为所有玩家加载头像
        this.avatar = new Image()
        this.hasAvatar = false
        if (this.info.role !== 'AI') {
            try {
                if (this.info.photo && this.info.photo.trim() !== '') {
                    this.avatar.src = this.info.photo
                } else {
                    this.avatar.src = 'https://www.helloimg.com/i/2024/12/22/6767fd5a3cf23.jpg'
                }
            } catch (error) {
                console.error('获取用户头像失败:', error)
                this.avatar.src = 'https://www.helloimg.com/i/2024/12/22/6767fd5a3cf23.jpg'
            }
        }

        this.avatar.onload = () => {
            this.hasAvatar = true
        }
    }
    // 计算两点之间的距离
    get_dist(x1, y1, x2, y2) {
        return Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
    }

    // 移动到指定位置
    move_to(tx, ty) {
        this.move_length = this.get_dist(this.info.x, this.info.y, tx, ty)
        let angle = Math.atan2(ty - this.info.y, tx - this.info.x)
        this.vx = Math.cos(angle)
        this.vy = Math.sin(angle)
    }
    // 初始化技能
    initialize_skills() {
        try {
            // 创建技能对象
            this.skills = {
                fireball: new Fireball(this),
                flash: new Flash(this),
                heal: new Heal(this)
            };
            
            // 默认选择火球技能
            this.currentSkill = null;
            
            console.log(`玩家 ${this.info.userId || this.info.role} 技能系统初始化完成`);
        } catch (error) {
            console.error('初始化技能系统时出错:', error);
            // 确保至少创建一个空的skills对象防止null引用错误
            this.skills = {};
        }
    }

    // 接收输入
    add_listening_events() {
        let outer = this
        const canvas = this.gameMap.ctx.canvas
        canvas.addEventListener('mousedown', (e) => {
            // 如果玩家已死亡，则不响应任何输入
            if (outer.is_dead) return

            const rect = canvas.getBoundingClientRect()//获取canvas的坐标
            const clickX = e.clientX - rect.left//获取点击的x坐标
            const clickY = e.clientY - rect.top//获取点击的y坐标
            // 右键
            if (e.button === 2) {
                // 先本地执行移动，保证UI响应迅速
                outer.move_to(clickX, clickY)

                // 在多人游戏中发送移动消息到服务器
                if (this.info.role === 'me' && this.gameMap.constructor.name === 'GameMap') {
                    const userStore = useUserStore() // 获取用户store实例
                    const gameStore = useGameStore() // 获取游戏store实例

                    // 发送移动消息
                    if (gameStore.socket && gameStore.socket.readyState === WebSocket.OPEN) {
                        try {
                            // 计算相对于canvas的比例坐标 (0-1范围)
                            const relativeTx = clickX / this.gameMap.width
                            const relativeTy = clickY / this.gameMap.height
                            const relativeX = this.info.x / this.gameMap.width
                            const relativeY = this.info.y / this.gameMap.height

                            const moveData = {
                                event: 'move',
                                userId: userStore.id,
                                tx: relativeTx,
                                ty: relativeTy,
                                x: relativeX,
                                y: relativeY,
                            }

                            gameStore.socket.send(JSON.stringify(moveData))
                        } catch (e) {
                            console.error('发送移动消息时出错:', e)
                        }
                    }
                }
            } else if (e.button === 0) {
                // 确保技能系统已初始化
                if (!this.skills) return;
                
                if (this.currentSkill && this.skills[this.currentSkill]) {
                    const skill = this.skills[this.currentSkill]
                    
                    // 在多人游戏中，需要先发送技能事件到服务器
                    if (this.info.role === 'me' && this.gameMap.constructor.name === 'GameMap') {
                        const gameStore = useGameStore()
                        const userStore = useUserStore()
                        
                        // 确保WebSocket连接有效
                        if (gameStore.socket && gameStore.socket.readyState === WebSocket.OPEN) {
                            // 计算相对于canvas的比例坐标 (0-1范围)
                            const relativeTx = clickX / this.gameMap.width
                            const relativeTy = clickY / this.gameMap.height
                            const relativeX = this.info.x / this.gameMap.width
                            const relativeY = this.info.y / this.gameMap.height
                            
                            // 根据技能类型发送不同消息
                            if (this.currentSkill === 'fireball') {
                                // 本地施放火球技能
                                const success = skill.cast(clickX, clickY)
                                
                                if (success) {
                                    // 发送火球事件
                                    gameStore.socket.send(
                                        JSON.stringify({
                                            event: 'shoot-fireball',
                                            userId: userStore.id,
                                            tx: relativeTx,
                                            ty: relativeTy,
                                            x: relativeX,
                                            y: relativeY,
                                        })
                                    )
                                }
                            } else if (this.currentSkill === 'flash') {
                                // 发送闪现事件到服务器
                                gameStore.socket.send(
                                    JSON.stringify({
                                        event: 'flash',
                                        userId: userStore.id,
                                        tx: relativeTx,
                                        ty: relativeTy,
                                        x: relativeX,
                                        y: relativeY
                                    })
                                )
                                
                                // 本地施放闪现效果，仅用于立即显示视觉效果
                                // 实际的位置更新将由服务器返回后应用
                                skill.cast(clickX, clickY)
                            }
                        }
                    } else {
                        // 单人游戏模式直接本地施放技能
                        skill.cast(clickX, clickY)
                    }
                }
            }
        })
        window.addEventListener('keydown', (e) => {
            // 如果玩家已死亡，则不响应任何输入
            if (outer.is_dead) return

            // 确保技能系统已初始化
            if (!this.skills) return;

            switch (e.key) {
                case this.skills['fireball'].skillKey:
                    this.currentSkill = 'fireball';
                    break;
                case this.skills['flash'].skillKey:
                    this.currentSkill = 'flash';
                    break;
                case this.skills['heal'].skillKey:
                    // 治疗技能不需要鼠标点击，按E键时直接释放
                    this.currentSkill = 'heal';
                    
                    // 直接施放治疗技能
                    if (this.skills.heal) {
                        // 在多人游戏模式下发送治疗事件到服务器
                        if (this.info.role === 'me' && this.gameMap.constructor.name === 'GameMap') {
                            const gameStore = useGameStore();
                            const userStore = useUserStore();
                            
                            // 先调用cast方法检查冷却时间
                            if (this.skills.heal.cast()) {
                                // 确保WebSocket连接有效
                                if (gameStore.socket && gameStore.socket.readyState === WebSocket.OPEN) {
                                    // 发送治疗事件
                                    gameStore.socket.send(
                                        JSON.stringify({
                                            event: 'heal',
                                            userId: userStore.id
                                        })
                                    );
                                    
                                    // 本地创建治疗效果
                                    this.skills.heal.create_heal_effect();
                                }
                            } else {
                                console.log('治疗技能在冷却中，无法使用');
                            }
                        } else {
                            // 单人游戏模式直接施放治疗
                            this.skills.heal.cast();
                        }
                    }
                    break;
            }
        })
        window.addEventListener('keyup', (e) => {
            // 如果玩家已死亡，则不响应任何输入
            if (outer.is_dead) return

            // 确保技能系统已初始化
            if (!this.skills) return;

            switch (e.key) {
                case this.skills['fireball'].skillKey:
                    if (this.currentSkill === 'fireball') {
                        this.currentSkill = null;
                    }
                    break;
                case this.skills['flash'].skillKey:
                    if (this.currentSkill === 'flash') {
                        this.currentSkill = null;
                    }
                    break;
                case this.skills['heal'].skillKey:
                    if (this.currentSkill === 'heal') {
                        this.currentSkill = null;
                    }
                    break;
            }
        })
    }

    // 受到攻击 - 只处理视觉效果
    is_attacked(angle, damage) {
        // 创建受击特效粒子
        for (let i = 0; i < 20 + Math.random() * 10; i++) {
            let x = this.info.x
            let y = this.info.y
            let radius = this.info.radius * Math.random() * 0.1
            let particleAngle = Math.PI * 2 * Math.random()
            let vx = Math.cos(particleAngle)
            let vy = Math.sin(particleAngle)
            let color = this.info.color
            let speed = this.info.speed * 10
            let move_length = this.info.radius * Math.random() * 10

            new Particle(this.gameMap, {
                x: x,
                y: y,
                vx: vx,
                vy: vy,
                radius: radius,
                color: color,
                speed: speed,
                move_length: move_length,
            })
        }

        this.damageX = Math.cos(angle)
        this.damageY = Math.sin(angle)

        // 调整击退效果的强度，减小系数避免击退过强
        this.damageSpeed = damage * this.height * 0.05

        if (this.gameMap.constructor.name === 'SingleMap') { 
            this.info.hp -= damage;
        }

        // 强制重新渲染一次，确保血量条更新
        if (this.gameMap) {
            this.render()
        }
    }

    // 添加处理服务器命中事件的方法
    handleHitEvent(data) {
        try {
            // 检查玩家是否已经被标记为死亡
            if (this.is_dead) {
                console.warn(`警告: 尝试对已死亡的玩家 ${this.info.userId} 应用伤害，操作被忽略`)
                return
            }

            // 更新血量并确保是数字类型
            this.info.hp = parseFloat(data.remainingHp)
            if (isNaN(this.info.hp)) {
                console.error(`血量转换为数字失败: ${data.remainingHp}`)
                this.info.hp = 0 // 死亡处理
            }

            // 计算火球击中角度（从火球位置到玩家位置）
            let angle

            // 检查是否有火球位置信息
            if (data.fireballX !== undefined && data.fireballY !== undefined) {
                // 转换为实际坐标
                const actualFireballX = data.fireballX * this.gameMap.width
                const actualFireballY = data.fireballY * this.gameMap.height

                const dx = this.info.x - actualFireballX
                const dy = this.info.y - actualFireballY
                angle = Math.atan2(dy, dx)
            } else {
                // 如果没有火球位置，则使用默认角度(随机方向)
                angle = Math.random() * Math.PI * 2
            }

            // 触发击退效果 - 增加力度到40使效果更明显
            this.is_attacked(angle, 40)

            // 触发血量重新渲染
            this.needsHealthRender = true

            // 检查是否死亡
            if (this.info.hp <= 0) {
                this.set_death()
            }

            // 强制重新渲染一次，确保玩家可见
            this.render()
        } catch (error) {
            console.error(`处理击中事件时出错:`, error)
        }
    }

    // 设置玩家死亡状态
    set_death() {
        if (!this.is_dead) {
            this.is_dead = true
            this.info.hp = 0

            // 仅在本地处理死亡效果，不再向后端发送死亡事件
            // 如果gameMap存在，仍然调用playerDeath用于更新UI
            if (this.gameMap && typeof this.gameMap.playerDeath === 'function') {
                this.gameMap.playerDeath(this)
            }
        }
    }

    // 根据难度更新AI玩家的行为
    update_AI_behavior() {
        // 只在AI模式下执行AI行为
        if (this.info.role === 'AI' && this.gameMap.constructor.name === 'SingleMap') {
            // 检查玩家是否死亡
            if (this.info.hp <= 0) {
                if (!this.is_dead) {
                    this.set_death()
                }
                return;
            }

            // 确保AI玩家初始化了技能系统
            if (!this.skills) {
                this.initialize_skills();
            }

            // 根据不同难度调整AI行为
            let attackProbability = 0.01; // 默认攻击概率
            let healProbability = 0.005; // 默认治疗概率

            if (this.gameMap.difficulty === 'first') {
                attackProbability = 0.02; // 简单难度
                healProbability = 0.01;
            } else if (this.gameMap.difficulty === 'second') {
                attackProbability = 0.04; // 中等难度
                healProbability = 0.02;
            } else if (this.gameMap.difficulty === 'third') {
                attackProbability = 0.08; // 高难度 - 增加攻击频率
                healProbability = 0.04;   // 增加治疗频率
            }

            // 寻找玩家角色
            let player = null;
            for (let i = 0; i < this.gameMap.players.length; i++) {
                if (this.gameMap.players[i].info.role === 'me' && !this.gameMap.players[i].is_dead) {
                    player = this.gameMap.players[i];
                    break;
                }
            }

            // 在血量低时尝试治疗
            if (this.info.hp < this.maxHp * 0.4 && Math.random() < healProbability) {
                // 使用治疗技能
                if (this.skills && this.skills.heal) {
                    this.skills.heal.cast();
                }
            }

            if (player) {
                // 概率性攻击，但确保AI之间有不同反应时间
                if (Math.random() < attackProbability) {
                    // 带有预测的攻击 - 预测玩家移动
                    const predictFactor = 0.8; // 预测系数
                    const tx = player.info.x + (player.vx * player.info.speed * this.timedelta / 1000) * predictFactor;
                    const ty = player.info.y + (player.vy * player.info.speed * this.timedelta / 1000) * predictFactor;
                    
                    // 施放火球技能
                    if (this.skills && this.skills.fireball) {
                        this.skills.fireball.cast(tx, ty);
                    }
                }

                // AI移动行为 - 随机在玩家周围移动或远离玩家
                if (Math.random() < 0.01) {
                    // 计算AI到玩家的距离
                    const dist = this.get_dist(this.info.x, this.info.y, player.info.x, player.info.y);
                    
                    if (dist < this.gameMap.height * 0.3) {
                        // 距离太近，远离玩家
                        const angle = Math.atan2(this.info.y - player.info.y, this.info.x - player.info.x);
                        const moveX = this.info.x + Math.cos(angle) * this.gameMap.width * 0.3;
                        const moveY = this.info.y + Math.sin(angle) * this.gameMap.height * 0.3;
                        this.move_to(moveX, moveY);
                    } else if (dist > this.gameMap.height * 0.7) {
                        // 距离太远，接近玩家
                        const angle = Math.atan2(player.info.y - this.info.y, player.info.x - this.info.x);
                        const moveX = this.info.x + Math.cos(angle) * this.gameMap.width * 0.3;
                        const moveY = this.info.y + Math.sin(angle) * this.gameMap.height * 0.3;
                        this.move_to(moveX, moveY);
                    } else {
                        // 保持适当距离，随机移动
                        const randomAngle = Math.random() * Math.PI * 2;
                        const moveX = this.info.x + Math.cos(randomAngle) * this.gameMap.width * 0.2;
                        const moveY = this.info.y + Math.sin(randomAngle) * this.gameMap.height * 0.2;
                        this.move_to(moveX, moveY);
                    }
                }
            } else {
                // 如果没有玩家或玩家已死亡，随机移动
                if (Math.random() < 0.01) {
                    let tx = Math.random() * this.width;
                    let ty = Math.random() * this.height;
                    this.move_to(tx, ty);
                }
            }
        }
    }

    update_Player_move() {
        if (this.damageSpeed > 10) {
            this.vx = this.vy = 0
            this.move_length = 0

            // 计算新位置
            let newX = this.info.x + (this.damageX * this.damageSpeed * this.timedelta) / 1000
            let newY = this.info.y + (this.damageY * this.damageSpeed * this.timedelta) / 1000

            // 限制玩家不会被击出边界 - 设置边界缓冲
            const buffer = this.info.radius * 2
            newX = Math.max(buffer, Math.min(this.width - buffer, newX))
            newY = Math.max(buffer, Math.min(this.height - buffer, newY))

            // 更新位置
            this.info.x = newX
            this.info.y = newY

            // 增加摩擦力，使玩家更快停下
            this.friction = 0.8

            // 减小击退速度
            this.damageSpeed *= this.friction
        } else {
            // 恢复正常摩擦力
            this.friction = 0.9

            if (this.move_length < this.eps) {
                this.vx = this.vy = 0
                this.move_length = 0
                // 只在AI模式下执行随机移动
                if (this.info.role === 'AI') {
                    let tx = Math.random() * this.width
                    let ty = Math.random() * this.height
                    this.move_to(tx, ty)
                }
            } else {
                let moved = Math.min(this.move_length, (this.info.speed * this.timedelta) / 1000)

                // 计算新位置
                let newX = this.info.x + this.vx * moved
                let newY = this.info.y + this.vy * moved

                // 限制玩家不会移出边界
                const buffer = this.info.radius * 2
                newX = Math.max(buffer, Math.min(this.width - buffer, newX))
                newY = Math.max(buffer, Math.min(this.height - buffer, newY))

                // 更新位置
                this.info.x = newX
                this.info.y = newY

                this.move_length -= moved
            }
        }
    }

    update() {
        // 检查生命值，判断是否死亡
        if (this.info.hp <= 0 && !this.is_dead) {
            this.set_death();
        }

        if (this.is_dead) {
            // 即使死亡也需要渲染，但不更新位置和响应操作
            this.render();
            return;
        }
        
        this.update_Player_move();
        this.update_AI_behavior();
        
        // 更新所有技能的冷却时间
        if (this.skills) {
            for (const skillKey in this.skills) {
                if (this.skills[skillKey] && typeof this.skills[skillKey].update === 'function') {
                    this.skills[skillKey].update();
                }
            }
        }

        this.render();
        
        // 添加对技能图标的渲染
        this.draw_skill_icon();
    }
    render() {
        // 安全检查：确保gameMap和ctx存在
        if (!this.gameMap || !this.gameMap.ctx) {
            console.warn(`玩家 ${this.info?.userId || 'unknown'} 无法渲染：GameMap或ctx不存在`)
            return
        }

        // 检查位置是否有效
        if (
            isNaN(this.info.x) ||
            isNaN(this.info.y) ||
            !isFinite(this.info.x) ||
            !isFinite(this.info.y)
        ) {
            console.warn(`玩家 ${this.info.userId} 位置无效: (${this.info.x}, ${this.info.y})`)
            return
        }

        // 确保血量是数字类型
        if (typeof this.info.hp !== 'number') {
            this.info.hp = parseFloat(this.info.hp) || 0
        }

        try {
            // 设置全局透明度 - 如果玩家已死亡则使用半透明效果
            this.gameMap.ctx.save()
            if (this.is_dead) {
                this.gameMap.ctx.globalAlpha = 0.4
            }

            // 计算血量比例 - 确保最小为0，最大为1
            const hpRatio = Math.max(0, Math.min(1, this.info.hp / this.maxHp))

            // 计算血条的宽度和半径
            const healthBarWidth = this.info.radius * 0.2
            const healthBarRadius = this.info.radius + healthBarWidth / 2

            // 活着的玩家才显示血条
            if (hpRatio > 0 && !this.is_dead) {
                this.gameMap.ctx.beginPath()
                // 从顶部开始，顺时针绘制血条，长度根据血量比例计算
                const startAngle = -Math.PI / 2 // 从顶部开始
                const endAngle = startAngle + Math.PI * 2 * hpRatio

                // 创建渐变
                let gradient
                // 健康状态 - 绿色渐变
                if (hpRatio > 0.6) {
                    // 确保参数有效
                    const x1 = this.info.x - healthBarRadius
                    const y1 = this.info.y - healthBarRadius
                    const x2 = this.info.x + healthBarRadius
                    const y2 = this.info.y + healthBarRadius

                    if (isFinite(x1) && isFinite(y1) && isFinite(x2) && isFinite(y2)) {
                        gradient = this.gameMap.ctx.createLinearGradient(x1, y1, x2, y2)
                        gradient.addColorStop(0, 'rgba(0, 255, 0, 0.7)')
                        gradient.addColorStop(0.5, 'rgba(50, 255, 50, 1)')
                        gradient.addColorStop(1, 'rgba(0, 200, 0, 0.8)')
                    } else {
                        // 使用备用颜色
                        gradient = 'rgba(0, 255, 0, 0.7)'
                    }
                    // 警告状态 - 黄色/橙色渐变
                } else if (hpRatio > 0.3) {
                    // 确保参数有效
                    const x1 = this.info.x - healthBarRadius
                    const y1 = this.info.y - healthBarRadius
                    const x2 = this.info.x + healthBarRadius
                    const y2 = this.info.y + healthBarRadius

                    if (isFinite(x1) && isFinite(y1) && isFinite(x2) && isFinite(y2)) {
                        gradient = this.gameMap.ctx.createLinearGradient(x1, y1, x2, y2)
                        gradient.addColorStop(0, 'rgba(255, 255, 0, 0.7)')
                        gradient.addColorStop(0.5, 'rgba(255, 165, 0, 1)')
                        gradient.addColorStop(1, 'rgba(255, 140, 0, 0.8)')
                    } else {
                        // 使用备用颜色
                        gradient = 'rgba(255, 165, 0, 0.8)'
                    }
                    // 危险状态 - 红色渐变
                } else {
                    // 确保参数有效
                    const x1 = this.info.x - healthBarRadius
                    const y1 = this.info.y - healthBarRadius
                    const x2 = this.info.x + healthBarRadius
                    const y2 = this.info.y + healthBarRadius

                    if (isFinite(x1) && isFinite(y1) && isFinite(x2) && isFinite(y2)) {
                        gradient = this.gameMap.ctx.createLinearGradient(x1, y1, x2, y2)
                        gradient.addColorStop(0, 'rgba(255, 50, 0, 0.7)')
                        gradient.addColorStop(0.5, 'rgba(255, 0, 0, 1)')
                        gradient.addColorStop(1, 'rgba(200, 0, 0, 0.8)')
                    } else {
                        // 使用备用颜色
                        gradient = 'rgba(255, 0, 0, 0.8)'
                    }
                }

                this.gameMap.ctx.arc(
                    this.info.x,
                    this.info.y,
                    healthBarRadius,
                    startAngle,
                    endAngle
                )
                this.gameMap.ctx.lineCap = 'round'
                this.gameMap.ctx.strokeStyle = gradient
                this.gameMap.ctx.lineWidth = healthBarWidth

                // 添加发光效果
                if (hpRatio < 0.3) {
                    // 血量低时闪烁效果
                    const pulseIntensity = Math.sin(Date.now() * 0.005) * 0.5 + 0.5
                    this.gameMap.ctx.shadowBlur = 10 + 5 * pulseIntensity
                    this.gameMap.ctx.shadowColor =
                        'rgba(255, 0, 0, ' + (0.7 + 0.3 * pulseIntensity) + ')'
                } else {
                    this.gameMap.ctx.shadowBlur = 10
                    this.gameMap.ctx.shadowColor =
                        hpRatio > 0.6 ? 'rgba(0, 255, 0, 0.7)' : 'rgba(255, 165, 0, 0.7)'
                }

                this.gameMap.ctx.stroke()
                this.gameMap.ctx.shadowBlur = 0 // 重置阴影
            }

            // 显示当前血量数值 - 仅对活着的玩家显示
            if (!this.is_dead) {
                this.gameMap.ctx.font = `${this.info.radius * 0.3}px Arial`
                this.gameMap.ctx.fillStyle = 'white'
                this.gameMap.ctx.textAlign = 'center'
                this.gameMap.ctx.fillText(
                    `${Math.round(this.info.hp)}`,
                    this.info.x,
                    this.info.y - this.info.radius - healthBarWidth
                )
            }

            // 使用玩家头像渲染
            if (this.hasAvatar) {
                this.gameMap.ctx.save()
                this.gameMap.ctx.beginPath()
                this.gameMap.ctx.arc(this.info.x, this.info.y, this.info.radius, 0, Math.PI * 2)
                this.gameMap.ctx.clip()
                this.gameMap.ctx.drawImage(
                    this.avatar,
                    this.info.x - this.info.radius,
                    this.info.y - this.info.radius,
                    this.info.radius * 2,
                    this.info.radius * 2
                )
                this.gameMap.ctx.restore()
                // 使用普通颜色渲染
            } else {
                this.gameMap.ctx.beginPath()
                this.gameMap.ctx.fillStyle = this.info.color
                this.gameMap.ctx.arc(this.info.x, this.info.y, this.info.radius, 0, Math.PI * 2)
                this.gameMap.ctx.fill()
            }

            // 在玩家上方显示用户名
            this.gameMap.ctx.font = `${this.info.radius * 0.4}px Arial`
            this.gameMap.ctx.fillStyle = 'white'
            this.gameMap.ctx.textAlign = 'center'
            this.gameMap.ctx.fillText(
                this.info.username || 'Player',
                this.info.x,
                this.info.y - this.info.radius * 1.5
            )

            // 为死亡玩家添加X形状标记
            if (this.is_dead) {
                const xSize = this.info.radius * 0.8
                const lineWidth = this.info.radius * 0.15

                // 设置X标记样式
                this.gameMap.ctx.lineWidth = lineWidth
                this.gameMap.ctx.strokeStyle = 'rgba(255, 0, 0, 0.8)'

                // 绘制X的第一条线 (左上到右下)
                this.gameMap.ctx.beginPath()
                this.gameMap.ctx.moveTo(this.info.x - xSize, this.info.y - xSize)
                this.gameMap.ctx.lineTo(this.info.x + xSize, this.info.y + xSize)
                this.gameMap.ctx.stroke()

                // 绘制X的第二条线 (右上到左下)
                this.gameMap.ctx.beginPath()
                this.gameMap.ctx.moveTo(this.info.x + xSize, this.info.y - xSize)
                this.gameMap.ctx.lineTo(this.info.x - xSize, this.info.y + xSize)
                this.gameMap.ctx.stroke()
            }

            // 恢复画布状态
            this.gameMap.ctx.restore()
        } catch (error) {
            console.error(`玩家 ${this.info.userId} 渲染出错:`, error)
        }
    }
    // 绘制技能图标
    draw_skill_icon() {
        if (this.info.role !== 'me' || !this.skills) {
            return
        }

        try {
            const scale = this.height
            // 图标位置放在右下角
            const baseX = this.width * 0.85 / scale // 将图标放在屏幕右侧85%位置
            const y = this.height * 0.9 / scale // 将图标放在屏幕底部90%位置
            const r = this.height * 0.04 / scale // 图标半径
            
            // 移除调试输出以避免控制台刷屏
            
            // 渲染每个技能图标
            let skillIndex = 0
            for (const skillKey in this.skills) {
                const skill = this.skills[skillKey]
                // 每个图标的间距为2.5倍半径
                const x = baseX - skillIndex * (r * 2.5)
                
                // 确保技能有绘制方法
                if (skill && typeof skill.draw_skill_icon === 'function') {
                    // 绘制技能图标和冷却
                    skill.draw_skill_icon(x, y, r, scale)
                }

                skillIndex++
            }
        } catch (error) {
            // 这里不需要每帧都记录错误，只在第一次发生时记录
            if (!this._skillDrawErrorLogged) {
                console.error("绘制技能图标时出错:", error);
                this._skillDrawErrorLogged = true;
            }
        }
    }
    start() {
        if (this.info.role === 'me') {
            this.add_listening_events()
        }
    }

    // 销毁玩家之前，从游戏地图中移除玩家
    on_destroy() {
        // 安全检查：确保gameMap存在
        if (this.gameMap && typeof this.gameMap.removePlayer === 'function') {
            this.gameMap.removePlayer(this);
        }
        
        // 清理其他资源
        if (this.skills) {
            this.skills = null;
        }
    }

    // 发射火球的方法 - 用于联机模式接收服务器火球事件后创建火球
    shoot_fireball(tx, ty) {
        try {
            // 确保技能系统已初始化
            if (!this.skills) {
                this.initialize_skills();
            }
            
            // 确保火球技能存在
            if (this.skills && this.skills.fireball) {
                // 由于这是从服务器接收的指令，我们不检查冷却时间
                // 仅创建火球实体用于前端显示
                if (typeof this.skills.fireball.createFireballEntity === 'function') {
                    // 计算方向向量
                    const angle = Math.atan2(ty - this.info.y, tx - this.info.x);
                    const vx = Math.cos(angle);
                    const vy = Math.sin(angle);
                    
                    // 直接创建火球实体
                    this.skills.fireball.createFireballEntity(vx, vy);
                    return true;
                }
            }
            
            return false;
        } catch (error) {
            console.error('发射火球时出错:', error);
            return false;
        }
    }
}
